/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "global_conf.h"

#include <fstream>
#include <mutex>
#include <new>

#include "glog/logging.h"

namespace os {
namespace v2x {
namespace protocol {

GlobalConf::GlobalConf() { InitRscuSn("/etc/v2x/SN"); }

GlobalConf *GlobalConf::Instance(bool create_if_needed) {
  static GlobalConf *instance = nullptr;
  if (!instance && create_if_needed) {
    static std::once_flag flag;
    std::call_once(flag, [&] { instance = new (std::nothrow) GlobalConf(); });
  }
  return instance;
}

void GlobalConf::InitRscuSn(const std::string &file) {
  rscu_sn_ = "default";
  std::ifstream ifs(file);
  if (!ifs.is_open()) {
    LOG(ERROR) << "Get RSCU SN Fail." << file;
    return;
  }
  std::string content((std::istreambuf_iterator<char>(ifs)),
                      (std::istreambuf_iterator<char>()));

  LOG(INFO) << "Get RSCU SN: " << content;
  size_t n = content.find_last_not_of("\r\n\t");
  if (n != std::string::npos) {
    content.erase(n + 1, content.size() - n);
  }
  rscu_sn_ = std::move(content);
  return;
}

}  // namespace protocol
}  // namespace v2x
}  // namespace os